package com.qifenqian.turbot.module.ui.dish

import android.content.Context
import android.content.Intent
import android.os.Parcelable
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.qifenqian.turbot.R
import com.qifenqian.turbot.base.BaseActivity
import com.qifenqian.turbot.config.ConfigType
import com.qifenqian.turbot.config.Constant
import com.qifenqian.turbot.module.contract.DishContract
import com.qifenqian.turbot.module.entity.request.DishAddEditRequest
import com.qifenqian.turbot.module.entity.response.UploadEntity
import com.qifenqian.turbot.module.entity.response.dish.CategoryEntity
import com.qifenqian.turbot.module.entity.response.dish.DishEntity
import com.qifenqian.turbot.module.presenter.DishPresenter
import com.qifenqian.turbot.util.MyGlideEngine
import com.qifenqian.turbot.util.SpUtils
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.internal.entity.CaptureStrategy
import kotlinx.android.synthetic.main.activity_dish_edit.*
import org.jetbrains.anko.selector
import org.jetbrains.anko.toast

private const val OPERATION_TYPE_DISH = "type"
private const val CURRENT_PAGE = "currentPage"
private const val ALL_CATEGORY_ENTITY = "all_category"
private const val DISH_ENTITY = "dishEntity"
private const val REQUEST_IMAGE_CHOOSE_DISH = 0x874
/**
 * @author H
 * @createDate 2019/1/8 14:32
 * @description 菜品编辑和添加
 * @see
 * @since
 */
class DishEditActivity : BaseActivity<DishPresenter, DishContract.View>(), DishContract.View {
    companion object {
        fun startThis(context: Context, type: Int, currentPage: Int, categoryEntities: List<CategoryEntity>, dishEntity: DishEntity? = null) {
            val intent = Intent(context, DishEditActivity::class.java)
            intent.putExtra(OPERATION_TYPE_DISH, type)
            intent.putExtra(CURRENT_PAGE, currentPage)
            intent.putParcelableArrayListExtra(ALL_CATEGORY_ENTITY, categoryEntities as ArrayList<out Parcelable>)
            intent.putExtra(DISH_ENTITY, dishEntity)
            context.startActivity(intent)
        }
    }

    override fun bindLayoutId(): Int {
        return R.layout.activity_dish_edit
    }

    override fun bindPresenter(): DishPresenter? {
        return DishPresenter(this, this)
    }

    private var mDishTypeId: Int = -1   //选择的菜系的id, 用于上传
    private var mOperationType: Int = ConfigType.TYPE_DISH_ADD   //添加还是编辑菜品
    private var mCurrentPage: Int = -1
    private var mCategoryEntities: List<CategoryEntity> = mutableListOf()   //传递来的菜类实体类集合
    private var mCategoryNameList: MutableList<String> = mutableListOf()    //菜类名字列表
    private var mCategoryIdList: MutableList<Int> = mutableListOf()         //菜类id列表
    private var mDishEntity: DishEntity? = null   //传递来的菜类实体类集合
    private var mDishPhoto: String = ""
    override fun initial() {
        mOperationType = intent.getIntExtra(OPERATION_TYPE_DISH, -1)
        mCurrentPage = intent.getIntExtra(CURRENT_PAGE, -1)
        mCategoryEntities = intent.getParcelableArrayListExtra(ALL_CATEGORY_ENTITY)
        mDishTypeId = mCategoryEntities[mCurrentPage].id
        if (mOperationType == ConfigType.TYPE_DISH_ADD) {
            tv_dish_edit_title.text = "菜品添加"
            btn_dish_edit_delete.visibility = View.INVISIBLE
        } else {
            tv_dish_edit_title.text = "菜品编辑"
            btn_dish_edit_delete.visibility = View.VISIBLE
            mDishEntity = intent.getParcelableExtra(DISH_ENTITY)
            mDishPhoto = mDishEntity!!.dishPhotoPath
            et_dish_edit_name.setText(mDishEntity!!.dishName)
            val options = RequestOptions().error(R.mipmap.ic_launcher)
            Glide.with(this).load(mDishPhoto).apply(options).into(iv_dish_edit_photo)
            swi_dish_edit_special.isChecked = mDishEntity!!.isSpecialty == 1
            swi_dish_edit_size.isChecked = mDishEntity!!.isSetSize == 1
            if (swi_dish_edit_size.isChecked) { //打开规格
                ly_dish_edit_price.visibility = View.GONE
                ly_dish_edit_size.visibility = View.VISIBLE
            } else {                            //未打开规格
                ly_dish_edit_price.visibility = View.VISIBLE
                ly_dish_edit_size.visibility = View.GONE
                et_dish_edit_price.setText((mDishEntity!!.price / 100).toString())
            }
            val map: MutableMap<String, Double> = mutableMapOf<String, Double>()
            if (mDishEntity!!.isSetSize == 1) {
                for (size in mDishEntity!!.sizeList) {
                    map[size.dishSizeName] = size.price
                }
                et_dish_edit_price_small.setText(((map["小份"]!!) / 100).toString())
                et_dish_edit_price_middle.setText(((map["中份"]!!) / 100).toString())
                et_dish_edit_price_big.setText(((map["大份"]!!) / 100).toString())
            }
        }
        for (categoryEntity in mCategoryEntities) {
            mCategoryNameList.add(categoryEntity.dishTypeName)
            mCategoryIdList.add(categoryEntity.id)
        }
        tv_dish_edit_category.setOnClickListener {
            selector("请选择菜品分类", mCategoryNameList) { dialog, position ->
                tv_dish_edit_category.text = mCategoryNameList[position]
                mDishTypeId = mCategoryIdList[position]
                dialog.dismiss()
            }
        }
        iv_dish_edit_photo.setOnClickListener {
            chooseImage()
        }
        tv_dish_edit_category.text = mCategoryEntities[mCurrentPage].dishTypeName
        swi_dish_edit_size.setOnCheckedChangeListener { b, isChecked ->
            if (isChecked) {
                ly_dish_edit_price.visibility = View.GONE
                ly_dish_edit_size.visibility = View.VISIBLE
            } else {
                ly_dish_edit_price.visibility = View.VISIBLE
                ly_dish_edit_size.visibility = View.GONE
            }
        }
        btn_dish_edit_next.setOnClickListener {
            var sizeList: MutableList<DishAddEditRequest.Size> = mutableListOf()
            var price = 0
            val isSetSize = if (swi_dish_edit_size.isChecked) 1 else 0
            val isSpecialty = if (swi_dish_edit_special.isChecked) 1 else 0
            val dishId = if (mDishEntity == null) -1 else mDishEntity!!.id
//            if (iv_dish_edit_photo.tag != "image_ok") {
//                toast("请上传菜品图片")
//                return@setOnClickListener
//            }
            if (et_dish_edit_name.text.toString().isBlank()) {
                toast("请输入菜品名称")
                return@setOnClickListener
            }
            if (tv_dish_edit_category.text.toString() == "请选择菜系分类") {
                toast("请选择菜系分类")
                return@setOnClickListener
            }
            if (swi_dish_edit_size.isChecked) {
                if (et_dish_edit_price_small.text.toString().isBlank()) {
                    toast("请设置小份价格")
                    return@setOnClickListener
                }
                if (et_dish_edit_price_middle.text.toString().isBlank()) {
                    toast("请设置中份价格")
                    return@setOnClickListener
                }
                if (et_dish_edit_price_big.text.toString().isBlank()) {
                    toast("请设置大份价格")
                    return@setOnClickListener
                }
                val sizeBig: DishAddEditRequest.Size = DishAddEditRequest.Size("大份", (et_dish_edit_price_big.text.toString().toDouble() * 100).toInt())
                val sizeMiddle: DishAddEditRequest.Size = DishAddEditRequest.Size("中份", (et_dish_edit_price_middle.text.toString().toDouble() * 100).toInt())
                val sizeSmall: DishAddEditRequest.Size = DishAddEditRequest.Size("小份", (et_dish_edit_price_small.text.toString().toDouble() * 100).toInt())
                sizeList = mutableListOf(sizeBig, sizeMiddle, sizeSmall)
            } else {
                if (et_dish_edit_price.text.toString().isBlank()) {
                    toast("请设置价格")
                    return@setOnClickListener
                }
                price = (et_dish_edit_price.text.toString().toDouble() * 100).toInt()
            }
            val request = DishAddEditRequest(
                    et_dish_edit_name.text.toString().trim(),
                    mDishPhoto,
                    mDishTypeId,
                    isSpecialty,
                    price,
                    SpUtils.getInstance().getInt(Constant.SP_KEY_RESTAURANT_ID, -1, Constant.SP_ACCOUNT),   //编辑不需要该字段
                    isSetSize,
                    sizeList,
                    dishId)     //添加不需要该字段
            if (mOperationType == ConfigType.TYPE_DISH_ADD) {
                mPresenter!!.addDish(request)
            } else {
                mPresenter!!.editDish(request)
            }
        }
        btn_dish_edit_delete.setOnClickListener {
            mPresenter!!.deleteDish(mDishEntity!!.id)
        }
    }

    private fun chooseImage() {
        Matisse.from(this@DishEditActivity)
                .choose(MimeType.ofImage())
                .countable(false)
                .capture(true)
                .captureStrategy(CaptureStrategy(true, Constant.AUTHORITY))
                .maxSelectable(1)
                .originalEnable(true)
                .maxOriginalSize(10)
                .imageEngine(MyGlideEngine())
                .forResult(REQUEST_IMAGE_CHOOSE_DISH)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_CHOOSE_DISH && resultCode == RESULT_OK) {
            mPresenter!!.uploadFile(Matisse.obtainPathResult(data)[0])
        }
    }

    override fun addDishResult(isSuccess: Boolean, code: Int, msg: String?, dishEntity: DishEntity?) {
        if (isSuccess) {
            finish()
        }
        toast(msg!!)
    }

    override fun editDishResult(isSuccess: Boolean, code: Int, msg: String?) {
        if (isSuccess) {
            finish()
        }
        toast(msg!!)
    }

    override fun deleteDishResult(isSuccess: Boolean, code: Int, msg: String?) {
        if (isSuccess) {
            finish()
        }
        toast(msg!!)
    }

    override fun uploadFileResult(isSuccess: Boolean, code: Int, msg: String?, uploadEntity: UploadEntity?) {
        if (isSuccess) {
            toast("上传成功")
            mDishPhoto = uploadEntity!!.url
            Glide.with(this)
                    .load(mDishPhoto)
                    .into(iv_dish_edit_photo)
            iv_dish_edit_photo.tag = "image_ok"
        } else {
            toast("上传失败")
        }
    }
}
